import { clerkMiddleware, createRouteMatcher } from '@clerk/nextjs/server';
import { NextResponse } from 'next/server';

// 方式一: 保护需要保护的路由
// const isProtectedRoute = createRouteMatcher(["/user-profile"]);
// export default clerkMiddleware(async (auth, req) => {
//     // protect()会重定向到登陆页面
//     if (isProtectedRoute(req)) await auth.protect();
// });

// 方式二：保护除了公共路由外的路由
// const isPublicRoute = createRouteMatcher(["/", "/sign-in(.*)", "/sign-up(.*)"]);
// export default clerkMiddleware(async (auth, req) => {
//     if (!isPublicRoute(req)) await auth.protect();
// });

//方式三：自定义重定向
const isPublicRoute = createRouteMatcher(["/", "/sign-in(.*)", "/sign-up(.*)"]); 

const isAdminRoute = createRouteMatcher(["/admin(.*)"]);

export default clerkMiddleware(async (auth, req) => {
    const {userId, redirectToSignIn} = await auth();

    if(isAdminRoute(req) && ((await auth()).sessionClaims?.metadata?.role !== "admin")){
        const url = new URL("/", req.url);
        return NextResponse.redirect(url);
    }

    if(!userId && !isPublicRoute(req)){
        // 添加自定义逻辑以在重定向之前运行
        // 如果用户未登录且访问的不是公共路由，则重定向到登录页面
        return redirectToSignIn();
    }
});


export const config = {
    matcher: [
        // Skip Next.js internals and all static files, unless found in search params
        '/((?!_next|[^?]*\\.(?:html?|css|js(?!on)|jpe?g|webp|png|gif|svg|ttf|woff2?|ico|csv|docx?|xlsx?|zip|webmanifest)).*)',
        // Always run for API routes
        '/(api|trpc)(.*)',
    ],
};